<template>
  <!-- 外部容器 -->
  <view class="container">
    <!-- 发布类型（从shop_type表获取） -->
    <view class="publish-type-section">
      <view class="section-title">商品分类</view>
      <view class="type-buttons">
        <up-tag
            :text="type.type"
        size="mini"
        type="success"
        class="type-button"
        :active="selectedTypeId === type.id"
        @click="handleTypeClick(type)"
        v-for="type in publishTypes"
        :key="type.id"
        >
        </up-tag>
      </view>
    </view>

    <!-- 表单组件 -->
    <up-form
        labelPosition="top"
        :model="formData"
        ref="formRef"
    >
      <!-- 宝贝标题 -->
      <up-form-item
          label="宝贝标题"
          prop="title"
          :borderBottom="false"
      >
        <input
            class="title-input"
            v-model="formData.title"
            placeholder="请输入宝贝标题"
        />
      </up-form-item>

      <!-- 宝贝描述 -->
      <up-form-item
          label="宝贝描述"
          prop="description"
          :borderBottom="false"
      >
        <textarea
            class="description-input"
            v-model="formData.description"
            placeholder="请对商品的成色、参数、入手渠道、转手原因、购买原价、交易方式进行描述~"
        ></textarea>
      </up-form-item>

      <!-- 宝贝照片上传 -->
      <up-form-item
          label="宝贝照片"
          prop="files"
          :borderBottom="false"
      >
        <my-upload
            v-model:files="formData.files"
            :max-count="9"
            upload-url="http://localhost:10000/oss/upload"
            file-type="item-file"
            user-id="123"
            @on-upload-error="handleUploadError"
            ref="uploadComponent"
        ></my-upload>
      </up-form-item>

      <!-- 价格 -->
      <up-form-item
          label="价格"
          prop="price"
          :borderBottom="false"
      >
        <view class="publish-price-section">
          <view class="price-input-container">
            <input
                class="price-input"
                v-model="formData.price"
                placeholder="请输入价格"
                type="digit"
            />
            <text class="unit">元</text>
          </view>
        </view>
      </up-form-item>

      <!-- 立即发布按钮 -->
      <view class="form-button-container">
        <up-button
            class="publish-button"
            type="primary"
            @click="submitForm"
            :disabled="!formData.typeId"
        >
        立即发布
        </up-button>
      </view>
    </up-form>
  </view>
</template>

<script setup>
import { onMounted, ref } from "vue";
import MyUpload from "@/components/upload/my-upload.vue";
import { publishGoods } from "@/apis/publish";
import { selectType } from "@/apis/shopAPI";  // 从shop_type表获取分类
const userInfo = uni.getStorageSync('userInfo');
// 商品分类列表（适配shop_type表结构：{id, type}）
const publishTypes = ref([]);
// 选中的分类ID
const selectedTypeId = ref('');

// 表单数据
const formData = ref({
  userId: userInfo.userId,
  title: '',
  typeId: '',  // 对应shop_type表的id字段
  description: '',
  price: '',
  files: []
});

// 获取商品分类数据
onMounted(async () => {
  try {
    const res = await selectType();
    // 适配shop_type表返回的数据结构
    publishTypes.value = res.data.data || [];
    // 默认选中第一个分类（如果有数据）
    if (publishTypes.value.length > 0) {
      handleTypeClick(publishTypes.value[0]);
    }
  } catch (error) {
    console.error('获取商品分类失败:', error);
    uni.showToast({ title: '加载分类失败', icon: 'none' });
  }
});

// 处理分类选择
const handleTypeClick = (type) => {
  selectedTypeId.value = type.id;  // 绑定id
  formData.value.typeId = type.id;  // 关联到表单
};

// 处理上传错误
const handleUploadError = (error) => {
  console.error('上传错误:', error);
  uni.showToast({ title: '图片上传失败', icon: 'none' });
};

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.typeId) {
    uni.showToast({ title: '请选择商品分类', icon: 'none' });
    return;
  }
  if (!formData.value.title.trim()) {
    uni.showToast({ title: '请输入宝贝标题', icon: 'none' });
    return;
  }
  if (!formData.value.price) {
    uni.showToast({ title: '请输入商品价格', icon: 'none' });
    return;
  }

  // 构造提交数据（确保typeId正确传递）
  const postData = {
    ...formData.value,
    price: parseFloat(formData.value.price) || 0,
    createTime: new Date().toISOString(),
    file: JSON.stringify(formData.value.files || [])
  };

  try {
    await publishGoods(postData);
    uni.showToast({ title: '发布成功', icon: 'success' });
    // 延迟返回列表页
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    uni.showToast({ title: '发布失败', icon: 'none' });
    console.error('发布失败:', error);
  }
};
</script>

<style>
/* 全局样式 */
page {
  background-color: #f8f8f8;
  font-size: 28rpx;
  color: #333;
}

.container {
  width: 100%;
  min-height: 100vh;
  padding: 0 20rpx;
  box-sizing: border-box;
}

/* 分类选择区域 */
.publish-type-section {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
  padding-left: 5rpx;
}

.type-buttons {
  display: flex;
  flex-wrap: wrap;  /* 自动换行 */
  gap: 16rpx;
}

.type-button {
  padding: 0 24rpx;
  height: 64rpx;
  line-height: 64rpx;
  border-radius: 32rpx;
  font-size: 28rpx;
  cursor: pointer;
  transition: all 0.3s;
}

/* 未选中状态 */
.type-button:not(.active) {
  background-color: #f5f5f5;
  color: #666;
  border: 1rpx solid #eee;
}

/* 选中状态 */
.type-button.active {
  background-color: #e6f7ee;
  color: #00b42a;
  border: 1rpx solid #00b42a;
}

/* 表单样式 */
.up-form-item {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.title-input {
  width: 100%;
  height: 68rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.description-input {
  width: 100%;
  height: 200rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  line-height: 1.5;
  resize: none;
}

/* 价格输入区 */
.publish-price-section {
  display: flex;
  align-items: center;
}

.price-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.price-input {
  flex: 1;
  height: 68rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 32rpx;
  text-align: right;
}

.unit {
  margin-left: 10rpx;
  font-size: 32rpx;
  color: #666;
}

/* 发布按钮 */
.form-button-container {
  padding: 40rpx 20rpx;
}

.publish-button {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background-color: #333;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
}

.publish-button:disabled {
  background-color: #ccc;
  opacity: 0.7;
}
</style>